package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Setmeal;
import com.itheima.service.FoodService;
import com.itheima.service.MemberService;
import com.itheima.utils.AESUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

//处理会员相关操作
@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    //手机号快速登录
    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map) throws Exception {
        //获取手机号和验证码
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //从redis中获取保存的验证码
        Jedis jedisPoolResource = jedisPool.getResource();
        String validateCodeInRedis = jedisPoolResource.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        //判断验证码是否输入正确
        if (validateCode!=null && validateCodeInRedis!=null && validateCode.equals(validateCodeInRedis)){
            //验证码输入正确
            //判断当前手机号用户是否为会员(查询会员表来确定)
            Member member = memberService.findByTelephone(telephone);
            if (member==null){
                //判断用户是否存在，如果为空则创建
                member = new Member();
                //不是会员，自动注册为会员（自动将当前用户保存到会员表）
                member.setRegTime(new Date());
                member.setPhoneNumber(telephone);
                memberService.add(member);
            }
            //登陆成功
            //向客户端浏览器写入cookie，内容为手机号,跟踪用户
            //将手机号进行AES加密后再返回客户端
            String aesEncrypt = AESUtils.aesEncrypt(telephone, AESUtils.key);
            Cookie cookie = new Cookie("login_member_telephone",aesEncrypt);
            cookie.setPath("/");    //路径
            cookie.setMaxAge(60*60*24*30);  //有效期30天
            response.addCookie(cookie);

            //新增修改点重新查询会员信息（查询会员id）
            Member byTelephone = memberService.findByTelephone(telephone);

            //保存会员信息到redis中，使用手机号作为key,保存时常为30分钟
            String json = JSON.toJSON(byTelephone).toString();
            Jedis resource = jedisPool.getResource();
            resource.setex(telephone,60*30,json);
            jedisPoolResource.close();
            resource.close();
            //返还结果
            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        }else {
            //验证码输入错误
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);
        }
    }

    /*//判定用户登录状态
    @RequestMapping("/checkLogin")
    public void checkLogin(HttpServletRequest res,HttpServletResponse resp) throws Exception {
        //获取客户端cookis
        Cookie[] cookies = res.getCookies();
        String telephone=null;
        if (null!=cookies){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if ("login_member_telephone".equals(name)){
                    //获取当前cookie的值
                    String value = cookie.getValue();
                    //使用AES算法进行value解密,该出直接异常抛出,后续进行手动处理
                    telephone = AESUtils.aesDecrypt(value, AESUtils.key);
                    break;
                }
            }
        }
        if (null==telephone){
            //res.getRequestDispatcher("/pages/login.html").forward(res,resp);
            resp.sendRedirect("/pages/login.html");
        }else{
            Jedis resource = jedisPool.getResource();
            String memberJSON = resource.get(telephone);
            if (memberJSON!=null){
                //res.getRequestDispatcher("/pages/member.html").forward(res,resp);
                resp.sendRedirect("/pages/member.html");
            }else{
                //res.getRequestDispatcher("/pages/login.html").forward(res,resp);
                resp.sendRedirect("/pages/login.html");
            }
            resource.close();
        }
    }*/

    //判定用户登录状态
    @RequestMapping("/checkLogin")
    public Result checkLogin(HttpServletRequest res) throws Exception {
        //获取客户端cookis
        Cookie[] cookies = res.getCookies();
        String telephone=null;
        if (null!=cookies){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if ("login_member_telephone".equals(name)){
                    //获取当前cookie的值
                    String value = cookie.getValue();
                    //使用AES算法进行value解密,该出直接异常抛出,后续进行手动处理
                    telephone = AESUtils.aesDecrypt(value, AESUtils.key);
                    break;
                }
            }
        }
        if (null==telephone){
            return new Result(false,"请重新登录!");
        }else{
            Jedis resource = jedisPool.getResource();
            String memberJSON = resource.get(telephone);
            //注意该memberJSON为JSON字符串,这里需要重新解析为对象,否则前端获取数据异常
            Member member = JSON.parseObject(memberJSON, Member.class);
            resource.close();
            if (memberJSON!=null){
                return new Result(true,"已登录!",member);
            }else{
                return new Result(false,"请重新登录!");
            }
        }
    }

    //退出登录
    /*@RequestMapping("/loginOut")
    public void loginOut(HttpServletRequest res,HttpServletResponse resp) throws Exception {
        //获取客户端cookis
        Cookie[] cookies = res.getCookies();
        String telephone=null;
        if (null!=cookies){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if ("login_member_telephone".equals(name)){
                    //获取当前cookie的值
                    String value = cookie.getValue();
                    //使用AES算法进行value解密,该出直接异常抛出,后续进行手动处理
                    telephone = AESUtils.aesDecrypt(value, AESUtils.key);
                    cookie.setValue(null);
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    resp.addCookie(cookie);
                    break;
                }
            }
        }
        if (null==telephone){
            //res.getRequestDispatcher("/pages/index.html").forward(res,resp);
            resp.sendRedirect("/pages/index.html");
        }else{
            Jedis resource = jedisPool.getResource();
            resource.del(telephone);
            //res.getRequestDispatcher("/pages/index.html").forward(res,resp);
            resp.sendRedirect("/pages/index.html");
            resource.close();
        }
    }*/
    //退出登录
    @RequestMapping("/loginOut")
    public Result loginOut(HttpServletRequest res,HttpServletResponse resp) throws Exception {
        //获取客户端cookis
        Cookie[] cookies = res.getCookies();
        String telephone=null;
        if (null!=cookies){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if ("login_member_telephone".equals(name)){
                    //获取当前cookie的值
                    String value = cookie.getValue();
                    //使用AES算法进行value解密,该出直接异常抛出,后续进行手动处理
                    telephone = AESUtils.aesDecrypt(value, AESUtils.key);
                    cookie.setValue(null);
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    resp.addCookie(cookie);
                    break;
                }
            }
        }
        if (null==telephone){
            return new Result(true,"请重新登录!");
        }else{
            Jedis resource = jedisPool.getResource();
            resource.del(telephone);
            resource.close();
            return new Result(true,"请重新登录!");
        }
    }
    //修改个人信息
    @RequestMapping("/editMemberInfo")
    public Result editMemberInfo(String validateCode,@RequestBody Member memberInfo,HttpServletResponse resp) throws Exception {
        //memberInfo中包含了id和手机号
        //获取手机号码
        String phoneNumber = memberInfo.getPhoneNumber();
        //获取redis连接将修改的后的memberInfo进行更新
        Jedis resource = jedisPool.getResource();
        //从redis中获取保存的验证码
        String validateCodeInRedis = resource.get(phoneNumber + RedisMessageConstant.SENDTYPE_LOGIN);
        //判断验证码是否输入正确
        if (!(validateCode!=null && validateCode.equals(validateCodeInRedis))){
            //验证码错误!
            //验证码输入错误
            resource.close();
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);

        }
        //验证码输入正确
        //根据手机号码查询用户对象
        try {
            Member byTelephone = memberService.findByTelephone(phoneNumber);
            //判断用户有无修改手机号码,修改后的手机号码是否已被占用
            if (byTelephone==null){
                //修改了手机号,且该手机号未被占用
                memberService.edit(memberInfo);

                //更新cookie信息
                //向客户端浏览器写入cookie，内容为手机号,跟踪用户
                //将手机号进行AES加密后再返回客户端
                String aesEncrypt = AESUtils.aesEncrypt(phoneNumber, AESUtils.key);
                Cookie cookie = new Cookie("login_member_telephone",aesEncrypt);
                cookie.setPath("/");    //路径
                cookie.setMaxAge(60*60*24*30);  //有效期30天
                resp.addCookie(cookie);

                //更新redis中的member信息
                resource.setex(memberInfo.getPhoneNumber(),60*30,JSON.toJSON(memberInfo).toString());
                resource.close();
                return new Result(true,"修改成功!");
            }else{
                if (memberInfo.getId().equals(byTelephone.getId())){
                    //未修改手机号
                    memberService.edit(memberInfo);

                    //更新redis中的member信息
                    resource.setex(memberInfo.getPhoneNumber(),60*30,JSON.toJSON(memberInfo).toString());
                    resource.close();
                    return new Result(true,"修改成功!");
                }else{
                    //修改了手机号,手机号已被占用
                    resource.close();
                    return new Result(false,"手机号已被占用!");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        resource.close();
        return new Result(false,"请稍后再试!");
    }

    @RequestMapping("/getAllMember")
   public Result getAllMember(){
        try {
            List<Member> memberList = memberService.finAll();
            //查询成功
            return new Result(true,MessageConstant.GET_SETMEAL_LIST_SUCCESS,memberList);
        } catch (Exception e) {
            e.printStackTrace();
            //查询套餐失败
            return new Result(false,MessageConstant.GET_SETMEAL_LIST_FAIL);
        }
   }
}
